/*
 *  This file is part of Bracket Security
 *  Copyright 2011 David R. Smith
 *
 */
package asia.redact.bracket.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;

/**
 * Password generator -
 * 
 * Using a random page from Wikipedia, generate some words. These can be used as a basis for passwords
 * or other uses.
 * 
 * This class does not work behind a firewall; it needs internet access to reach Wikipedia
 * 
 * @author Dave
 *
 */
public class RandomWordsImpl implements RandomWords {

	private String url = "http://en.wikipedia.org/wiki/Special:Random";
	private int minLength;
	private List<WordFilter> filters;
	private Random rand = new Random();
	private Set<String> list = new TreeSet<String>();
	
	public RandomWordsImpl(){
		minLength = 6;
		filters = new ArrayList<WordFilter>();
		StringBuffer buf = new StringBuffer();
		buf.append("http://");
		buf.append(Locale.getDefault().getLanguage());
		buf.append(".wikipedia.org/wiki/Special:Random");
		url = buf.toString();
	}
	
	public RandomWordsImpl(int minLength){
		this();
		this.minLength = minLength;
	}
	
	/**
	 * Note: wikipedia may not have all locales and I have not tried this with Kanji, etc.
	 * But it works with Italian.
	 * 
	 * @param minLength
	 * @param locale
	 */
	public RandomWordsImpl(int minLength, Locale locale){
		this();
		this.minLength = minLength;
		StringBuffer buf = new StringBuffer();
		buf.append("http://");
		buf.append(locale.getLanguage());
		buf.append(".wikipedia.org/wiki/Special:Random");
		url = buf.toString();
	}
	
	/* (non-Javadoc)
	 * @see org.dave.bracket.util.RandomWords#addWordFilter(org.dave.bracket.util.WordFilter)
	 */
	public void addWordFilter(WordFilter filter){
		filters.add(filter);
	}
	
	/* (non-Javadoc)
	 * @see org.dave.bracket.util.RandomWords#generate()
	 */
	public int generate(){
		URLGrabber grabber = new URLGrabber(url);
		String text = grabber.grab();
		list.clear();
		for(String s: text.split(" ")){
			if(s != null && s.length() > minLength){
				if(!s.matches("[a-zA-Z]+"))continue;
				if(filters.size() > 0) {
					for(WordFilter filter: filters){
						s = filter.filter(s);
					}
				}
				list.add(s);
			}
		}
		
		return list.size();
	}
	
	/* (non-Javadoc)
	 * @see org.dave.bracket.util.RandomWords#getRandomSelection()
	 */
	public String getRandomSelection() {
		if(list.size() == 0) throw new RuntimeException("No passwords available in list.");
		int index = rand.nextInt(list.size());
		return (String) list.toArray()[index];
	}

	/* (non-Javadoc)
	 * @see org.dave.bracket.util.RandomWords#getList()
	 */
	public Set<String> getList() {
		return list;
	}
}
